//
//  CCLoctionService.m
//  Party
//
//  Created by its on 15/3/17.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCLoctionService.h"
typedef void (^cityBlock)(NSString *);

@interface CCLoctionService()
@property (nonatomic, strong) CLLocationManager* locationManager;
@property (nonatomic, strong) cityBlock cityblock;
@end

@implementation CCLoctionService
//开始定位
-(void)startLocation {
  self.locationManager = [[CLLocationManager alloc] init];
  self.locationManager.delegate = self;
  self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
  self.locationManager.distanceFilter = 10.0f;
  if ([CLLocationManager locationServicesEnabled]) {
    if ([CLLocationManager authorizationStatus] < 3) {
      if (IOS_VERSION >= 8.0) {
        [self.locationManager requestAlwaysAuthorization];
      }
    }
     [self.locationManager startUpdatingLocation];
  } else {
    self.cityblock(nil);
  }
  
}

- (void) getCity:(void(^)(NSString *city))block {
  self.cityblock = block;
  [self startLocation];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
  
  [self.locationManager stopUpdatingLocation];
  CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
  [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
    for (CLPlacemark * placemark in placemarks) {
      NSDictionary *test = [placemark addressDictionary];
      self.cityblock(test[@"City"]);
    }
  }];
}

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
  [self locationManager:manager didUpdateToLocation:[locations lastObject] fromLocation:nil];
}

- (void) locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
  NSLog(@"authorization status: %d",status);
  if (status < 3) self.cityblock(nil);
}
@end
